package com.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.CustomException;
import com.reggie.common.R;
import com.reggie.pojo.Category;
import com.reggie.pojo.Dish;
import com.reggie.dto.DishDto;
import com.reggie.pojo.DishFlavor;
import com.reggie.service.ICategoryService;
import com.reggie.service.IDishFlavorService;
import com.reggie.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private IDishService dishService;
    @Autowired
    private IDishFlavorService dishFlavorService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name){
        //分页查询
        Page<Dish> pageBean = new Page<>(page,pageSize);
        //要返回的带有菜品分类名的dishDtoPage
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //模糊查询
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName,name);
        //排序
        lqw.orderByDesc(Dish::getUpdateTime);
        //获取分页数据(不带菜品分类名)
        dishService.page(pageBean,lqw);

        //把pageBean数据复制给dishDtoPage并返回
        BeanUtils.copyProperties(pageBean,dishDtoPage,"records");
        List<Dish> records = pageBean.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //把每个dish数据复制给dishDto
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类 id 0/1
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            //获取菜品分类的名字,设置给dishDto
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
            //带有菜品分类名的List<DishDto>
        }).collect(Collectors.toList());
        //list数据再塞给dishDtoPage并返回
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("删除菜品,ids为:{}",ids.toString());
        ArrayList<Integer> integers = new ArrayList<>();
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            Integer status = dish.getStatus();
            if (status == 1){
                integers.add(status);
            }
            if (status == 0){
                //删除禁用状态下的餐品
                dishService.removeById(id);
                //删除要删除的餐品对应的餐品口味
                LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
                lqw.eq(DishFlavor::getDishId,id);
                dishFlavorService.remove(lqw);
            }
        }
        if (ids.size() == integers.size()){//说明全都是启用
            return R.error("删除菜品失败");
        }//有禁用的菜品，删除禁用菜品，启用的不删
        return R.success("删除菜品成功");
    }


    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //清理缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改菜品信息成功！");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存数据
        List<DishDto> dishDtos = null;
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果存在，直接返回，无需查询数据库
        if (dishDtos != null){
            return R.success(dishDtos);
        }
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //传过来的dish中有相对应的套餐id且不为空
        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //只要状态为1(起售)的菜品
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);
        //-------客户端需要看到菜品口味，以下为修改内容-------------------

        dishDtos = list.stream().map((everyDish) ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(everyDish,dishDto);
            Category category = categoryService.getById(everyDish.getCategoryId());
            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            Long dishId = everyDish.getId();
            LambdaQueryWrapper<DishFlavor> dflqw = new LambdaQueryWrapper<>();
            dflqw.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(dflqw);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("status:{}",status);
        LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus,status);// set status = ?
        qw.in(Dish::getId,ids);//  where id in (1,2,3)
        dishService.update(qw);
        return R.success("操作成功");
    }
}
